<?php

	//Ex.: print_array(array(array("id" => 1, "name" => "nombre"), ... ));
	function print_array($arr){
		echo '<pre>'.nl2br(print_r($arr,true)).'</pre>';
	}

	//Ex.: leer("SELECT * FROM <table>");
	function leer($sql){
		$result = array();
		try{
			$resEmp = $GLOBALS['db']->query($sql);
			$count = 0;
			if ($resEmp->rowCount()> 0) {
				while ($rowEmp = $resEmp->fetch()) {
			  		$result[$count] = $rowEmp;
					$count++;
				}
			}
			return $result;
		}catch(PDOException $e){
			echo 'Fallo de conexion: ' . $e->getMessage();
			return -1;
		}
	}

	//Ex.: insertar("usuario", array("name" => "nombre", "surname1" => "apellido1", "surname2" => "apellido2", ... ));
	function insertar($table, $values, $i=false, $tipo_tabla=""){

		if($tipo_tabla == "RELACIONAL")
			$v = "('".(implode("','",$values))."')";
		else
			$v = "('','".(implode("','",$values))."')";

		
		$sql = "INSERT INTO ".$table." VALUES ".$v;
                
		try{

			$res = $GLOBALS['db']->exec($sql);
				if($i)
					return $GLOBALS['db']->lastInsertId();//mysql_insert_id();
		}catch(PDOException $e){
			echo 'Fallo de conexion: ' . $e->getMessage();
			if($i)
				return -1;
		}
		
	}

	//Ex.: modificar("usuario", array("id" => 1, "name" => "nombre"), "id = 1");
	function modificar($table, $data, $where){
		$values = "";
		foreach($data as $key => $data){

			if($values=="") $values .= "SET ";
			
                        if($values=="SET ") $values .= $key." = '".$data."'";
			else $values .= ", ".$key." = '".$data."'";
		}

		$operation = "UPDATE ".$table." ".$values." WHERE ".$where;

		try{
			$res = $GLOBALS['db']->exec($operation);//mysql_query($operation,$GLOBALS['db']) or die(mysql_error());

                }catch(PDOException $e){
			echo 'Fallo de conexion: ' . $e->getMessage();
		}
		
	}

	//Ex.: eliminar("usuario", "id", 2);
	function eliminar($table, $nombre, $valor){

		$sql = "DELETE FROM ".$table." WHERE ".$nombre." = ".$valor;

		try{
                  
                  	$res = $GLOBALS['db']->exec($sql);
			//$GLOBALS['db']->execute($sql);//mysql_query($sql,$GLOBALS['conexion']) or die(mysql_error());
		}catch(PDOException $e){
			echo 'Fallo de conexion: ' . $e->getMessage();
		}
	}


?>
